package com.gitee.exception;

import com.gitee.result.Result;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;
import java.security.SignatureException;

/**
 * @description: 全局处理自定义的业务异常
 * @author: chennl
 * @date: 2021/12/28
 * @version: 1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        log.error(e.getMessage(), e);
        return Result.error();
    }

    @ExceptionHandler(ServiceException.class)
    public Result serviceException(ServiceException e) {
        log.error(e.getMessage(), e);
        return Result.error();
    }

    @ResponseBody
    @ExceptionHandler(value = {ExpiredJwtException.class})
    public Result expiredJwtException(ExpiredJwtException e) {
        log.error(e.getMessage(), e);
        return Result.error("Token过期");
    }

    @ExceptionHandler(value = UnsupportedJwtException.class)
    @ResponseBody
    public Result unsupportedJwtException(UnsupportedJwtException e) {
        log.error(e.getMessage(), e);
        return Result.error("Token签名失败");
    }

    @ExceptionHandler(value = SignatureException.class)
    @ResponseBody
    public Result signatureException(SignatureException e) {
        log.error(e.getMessage(), e);
        return Result.error("Token格式错误");
    }

    @ExceptionHandler(value = AccessDeniedException.class)
    @ResponseBody
    public Result accessDeniedException(AccessDeniedException e) {
        log.error(e.getMessage(), e);
        return Result.error("Token非法参数异常");
    }

    @ExceptionHandler(value = MalformedJwtException.class)
    @ResponseBody
    public Result malformedJwtException(MalformedJwtException e) {
        log.error(e.getMessage(), e);
        return Result.error("Token没有被正确构造");
    }
}
